import Message from 'tdesign-miniprogram/message/index';
import Toast from 'tdesign-miniprogram/toast/index';

const {
  login
} = require('../../../api/index')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNumber: '',
    verificationCode: '',
    phoneError: false,
    codeErr: false,
    isCanFast: false,
    MoCodeMsg: '获取验证码', //文案
    MoMsgWait: 60, //时间秒
    MoDisabled: false,
    isGoHome: 1,
    backPageUrl: ""
  },

  inputChange: function (e) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  inputChangeCode: function (e) {
    this.setData({
      verificationCode: e.detail.value + ""
    })
  },
  selectConent(event) {
    this.setData({
      isCanFast: event.detail.isConsent
    })
  },
  sendSbinms() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '短信验证码发送成功，请注意查收',
    });
    this.setData({
      MoCodeMsg: '重新获取' + `(${this.data.MoMsgWait})`,
      MoMsgWait: this.data.MoMsgWait - 1,
      MoDisabled: true
    });
    let inter = setInterval(function () {
      this.setData({
        MoCodeMsg: '重新获取' + `(${this.data.MoMsgWait})`,
        MoColor: 'rgba(40, 200, 122, 1)',
        MoMsgWait: this.data.MoMsgWait - 1,
        MoDisabled: true
      });
      if (this.data.MoMsgWait < 0) {
        clearInterval(inter)
        this.setData({
          MoCodeMsg: "重新获取",
          MoMsgWait: 60,
          MoDisabled: false,
          MoColor: 'rgba(40, 200, 122, 1)'
        });
      }
      //注意后面的bind绑定，最关键。不然又是未定义，无法使用外围的变量;
    }.bind(this), 1000);
  },

  sendVerification() {
    if (this.data.MoDisabled) return
    if (!this.data.phoneNumber || this.data.phoneError) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '手机号不正确',
      });
      return
    }
    login.getVerificationCode({
      mobile: this.data.phoneNumber,
      scene: "login",
    }).then(res => {
      this.sendSbinms()
    })
  },
  // onConsentClose() {
  //   wx.reLaunch({
  //     url: '/pages/home/index',
  //   })
  // },
  loginForPhone() {
    if (this.data.codeErr || this.data.phoneError) return
    if (!this.data.phoneNumber || !this.data.verificationCode) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: !this.data.phoneNumber ? '手机号不能为空' : '验证码不能为空',
      });
      return
    }
    if (this.data.isCanFast) {
      wx.showLoading({
        title: '请稍后',
      })
      login.phoneAndWxLogin({
        mobile: this.data.phoneNumber,
        code: this.data.verificationCode,
        client_id: 'House_App',
        scope: 'openid profile house',
        grant_type: 'sms'
      }).then((res) => {
        if (res) {
          wx.setStorageSync('token', `${res.token_type} ${res.access_token}`)
          app.getUser().then((res) => {
            // this.selectComponent('#consent').handlePopup()
            if (res.IsNewUser) {
              app.globalData.sdk.register(res.UserId)
            }
            app.globalData.sdk.loggedin(res.UserId)
            app.getUserStatus(this).then((res) => {
              if (res.UserInfoStatus==0) {
                if (this.data.backUrl) {
                  wx.redirectTo({
                    url: '/' + this.data.backUrl,
                  })
                  return
                }
                if (this.data.isGoHome == 1) {
                  wx.reLaunch({
                    url: '/pages/ai/index',
                  })
                } else {
                  wx.navigateBack()
                }
              }
              wx.hideLoading()
              if (res.UserInfoStatus != 8) {
                app.loadSignalR()
              }
            })

          })
        }
      })
    } else {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 1000,
        content: '请先阅读并勾选用户协议和隐私协议',
      });
    }
  },
  onPhoneInput(e) {
    const {
      phoneError
    } = this.data;
    const isPhoneNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/.test(e.detail.value);
    if (phoneError === isPhoneNumber) {
      this.setData({
        phoneError: !isPhoneNumber,
      });
    }
  },
  onCodeInput(e) {
    const {
      codeErr
    } = this.data;
    if (!e.detail.value) return
    const isCodeString = /^\d{6}$/.test(e.detail.value);
    if (codeErr === isCodeString) {
      this.setData({
        codeErr: !isCodeString,
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let backPaageUrl = options.backPageUrl === 'undefined' ? '' : options.backPageUrl
    this.setData({
      isGoHome: options.isGoHome || 1,
      backUrl: backPaageUrl
    })
    // this.MosendSms()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})